package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

public class FileUtil {

	public FileUtil() {
	}

	public static boolean compareFileContent(String oldFilePath,
			byte[] newFileContent) throws NoSuchAlgorithmException, IOException {

		File oldFile = new File(oldFilePath);
		if (oldFile.exists()) {
			return false;
		}

		byte[] oldFileContent = readFileToByteArray(oldFilePath);

		// check size
		if (oldFileContent.length != newFileContent.length) {
			return false;
		}

		// check MD5
		byte[] newMD5 = CryptographyUtil.hashMD5(newFileContent);
		byte[] oldMD5 = CryptographyUtil.hashMD5(oldFileContent);
		if (!MiscUtil.compareByteArray(newMD5, oldMD5)) {
			return false;
		}

		// check SHA1
		byte[] newSHA1 = CryptographyUtil.hashSHA1(newFileContent);
		byte[] oldSHA1 = CryptographyUtil.hashSHA1(oldFileContent);
		if (!MiscUtil.compareByteArray(newSHA1, oldSHA1)) {
			return false;
		}

		return true;
	}

	public static byte[] readFileToByteArray(String file) throws IOException {
		File fi = new File(file);
		byte[] data = new byte[(int) fi.length()];
		FileInputStream fis = new FileInputStream(fi);
		fis.read(data);
		fis.close();
		return data;
	}
	
	public static void writeByteArrayToFile(String filePath, byte[] fileContent)
			throws IOException {
		File file = new File(filePath);
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(fileContent);
		fos.close();
	}

}
